package com.whl.sm.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whl.sm.mapper.system.SysDictMapper;
import com.whl.sm.model.system.SysDict;
import com.whl.sm.service.system.SysDictService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 数据字典表 服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2021-09-18
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {


    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public int update(SysDict sysDict) {
        sysDict.setDictKey(sysDict.getDictKey().toUpperCase());
        int result;
        if (StringUtils.isNotBlank(sysDict.getId())){
            result = getBaseMapper().updateById(sysDict);
        }
        else {
            Integer index = 1,level = 0;
            index = getBaseMapper().selectCount(new QueryWrapper<SysDict>()
                    .eq("dict_key",sysDict.getDictKey())
            );
            if(StringUtils.isNotBlank(sysDict.getParentId()) && sysDict.getParentId().equals("")){
                SysDict parent = getBaseMapper().selectById(sysDict.getParentId());
                level = parent==null?0:parent.getLevel()+1;
            }
            else {
                sysDict.setParentId("0");
            }
            sysDict.setDictIndex(index !=0? index+1:1);
            sysDict.setLevel(level);

            //插入
            result = getBaseMapper().insert(sysDict);

        }
        return result;
    }
}
